#include "qupfile.h"


namespace FileTransfer {


QUpFile::QUpFile(const QString &name,
                 const QByteArray &head,
                 const QByteArray &tail,
                 QObject *parent)
    : QIODevice(parent)
{
    file = new QFile(name, this);
    this->head = new QByteArray(head);
    this->tail = new QByteArray(tail);
    position = 0;
}


QUpFile::~QUpFile()
{
    delete head;
    delete tail;
}


qint64 QUpFile::readData(char *data, qint64 maxLength)
{
    if (!file->isOpen())
        return -1;

    char *pointer = data;
    qint64 atAll = 0;
    if ((position<head->size()) && (maxLength > 0)) {
        qint64 count = qMin(maxLength, (qint64)head->size());
        memcpy(pointer, head->data(), count);
        pointer += count;
        position += count;
        atAll += count;
        maxLength -= count;
    }
    if (maxLength > 0 && (position < sizeFull())) {
        qint64 count = qMin(maxLength, file->bytesAvailable());
        int size = file->read(pointer, count);
        pointer += size;
        maxLength -= size;
        position += size;
        atAll += size;
    }
    if (position>=sizePart() && (maxLength > 0) && (position < sizeFull())) {
        qint64 count = qMin(maxLength, (qint64)tail->size());
        memcpy(pointer, tail->data(), count);
        position += count;
        atAll += count;
    }
    return atAll;
}


qint64 QUpFile::writeData(const char *, qint64)
{
    return -1;
}


qint64 QUpFile::size() const
{
    return sizeFull();
}


bool QUpFile::openFile()
{
    if (file->open(QIODevice::ReadOnly))
        return this->open(QIODevice::ReadOnly);
    return false;
}


qint64 QUpFile::sizeFull() const
{
    return file->size() + head->size() + tail->size();
}


qint64 QUpFile::sizePart() const
{
    return head->size() + file->size();
}

} // namespace FileTransfer
